package m.html;

import m.common.action.VueResult;
import m.html.element.Element;
import m.html.element.other.IElement;
import m.html.form.FormEvent;
import m.html.form.IForm;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import m.system.util.StringUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class VueFormResult extends VueResult {
    private final List<IForm> formList=new ArrayList<>();
    public VueFormResult addForm(IForm form){
        formList.add(form);
        return this;
    }
    private Map<String,Object> datas;
    @Override
    public String outHtml() {
        try {
            datas=new HashMap<>();
            Map<String,String> watchs=new HashMap<>();
            List<FormEvent> methods=new ArrayList<>();
            List<String> mounteds=new ArrayList<>();
            StringBuilder sb=new StringBuilder();
            sb.append("{\n")
            .append(" template:`\n");
            for(int i=0;i<formList.size();i++){
                IForm form=formList.get(i);
                IElement ele= Element.tag("div").E(form.getElement(i==0));
                if(!form.isShowHead()&&i!=0) ele.A(":style","{padding:'15px'}");
                if(i!=0) ele.A("style","margin-top:-15px;");
                sb.append(ele.toString());
                datas.putAll(form.getData());
                watchs.putAll(form.getWatch());
                methods.addAll(form.getMethods());
                if(StringUtil.notSpace(form.getMounted())) mounteds.add(form.getMounted());
            }
            sb.append(" `,\n")
            .append(" props: ['localeZh','param','parentVue'],\n")
            .append(" data:function(){\n")
            .append("  return ").append(ObjectUtil.toString(datas)).append(";\n")
            .append(" },\n")
            .append(" watch:{\n");
            for(String wakey : watchs.keySet())
                sb.append("'").append(wakey).append("':function(newValue,oldValue){")
                    .append(watchs.get(wakey)).append("},\n");
            sb.append(" },\n")
            .append(" mounted(){\n");
            for(String mounted : mounteds) { if(StringUtil.notSpace(mounted)) sb.append(mounted).append("\n");}
            sb.append(" },\n")
            .append(" methods:Object.assign(mo.vueResult.methods,{\n");
            for(FormEvent fe : methods) sb.append(fe).append("\n");
            sb.append(" })\n")
            .append("}");
            return sb.toString();
        } catch (MException e) {
            return VueResult.toErrorPage(e.getMessage(),true).toString();
        }
    }
    @Override
    public String getContent() {
        return new JSONMessage().push("data",datas).toJSONString();
    }
}
